class DataFile < ActiveRecord::Base
  def self.save(upload)
    name =  upload['datafile'].original_filename
    directory = "public/data"
    # create the file path
    FileUtils.makedirs("#{RAILS_ROOT}/public/upload")
    path = File.join(directory, name)
    # write the file
    File.open(path, "wb") { |f| f.write(upload['datafile'].read) }
  end

  #上传zip文件
  def self.saveZip(upload)
    require 'ftools'
    require "fileutils.rb"
    #获取上传的文件名称
    uploadFile=  upload['datafile'].original_filename
    #获取当前时期
    timeStr = Time.now.strftime('%Y/%m/%d')
    #上传相对路径
    rel_path = File.join(timeStr,uploadFile.split(".")[0])
    #上传全部路径
    dirs=File.join($upload_path,rel_path)
    #上传zip源路径
    path = File.join(dirs, $src)
    #创建上传源文件夹
    File.makedirs path
    #创建存放大小图片的文件夹
    File.makedirs File.join(dirs, $small)
    File.makedirs File.join(dirs, $larger)
   
    #上传的物理文件名
    file_upload_name = File.join(path, uploadFile)
    File.open(file_upload_name, "wb") {
      |f| f.write(upload['datafile'].read)
    }
    require 'zip/zip'
    require 'zip/zipfilesystem'
    Zip::ZipFile::open(file_upload_name) {
      |zf| zf.each {
        |e|
        fpath = File.join(path, e.name)
        FileUtils.mkdir_p(File.dirname(fpath))
        zf.extract(e, fpath) } }
    return rel_path
  end

  #压缩图片
  def self.compress_pic dest,src,dsize
    require 'mini_magick'
    #得到源图片大小
    src_size = File.size src
    #得到源图片尺寸
    img = MiniMagick::Image.from_file src
    w,h = img[:width],img[:height]
    if w > dsize
      img.resize dsize
    end
    img.write dest
  end

  #根据传入的文件路径得到相应的图片
  def self.traverse_dir(file_path,src_array)
    if File.directory? file_path     
      Dir.foreach(file_path) do |file|
        if file!="." and file!=".."
          traverse_dir(file_path+"/"+file,src_array)
        end
      end
    elsif file_path[/\.gif$/] || file_path[/\.jpg$/]      
      src_array << file_path
    else     
    end
    return src_array
  end

end

